﻿using System;
using System.IO;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace NetFramework
{
    public class SocketServer : System.ComponentModel.Component
    {
        private int bufferSize = 2048;
        private string serverIP = "127.0.0.1";
        private int serverPort = 11000;

        private Socket listenerSocket = null;
        private Thread thread = null;

        private ManualResetEvent allDone = new ManualResetEvent(false);
        private ManualResetEvent sendDone = new ManualResetEvent(false);

        public SocketServer()
        {
            InitializeComponent();
            InitDevice("127.0.0.1", 11000, 2048);
        }

        public SocketServer(System.ComponentModel.IContainer container)
        {
            container.Add(this);
            InitializeComponent();
            InitDevice("127.0.0.1", 11000, 2048);
        }

        public event EventHandler EvtClientDisConnectedData = (s, e) => { };
        public event EventHandler EvtClientConnectedData = (s, e) => { };
        public event ReceiveDataEvent EvtReceiveData = (s, e) => { };
        public event ErrorServerEvent EvtServerError = (s, e) => { };

        protected virtual void OnClientDisConnectedEvent(string ip)
        {
            EvtClientDisConnectedData(ip, null);
        }
        protected virtual void OnClientConnectedEvent(string ip)
        {
            EvtClientConnectedData(ip, null);
        }
        protected virtual void OnReceiveEvent(ReceiveEventArgs e)
        {
            EvtReceiveData(this, e);
        }
        protected virtual void OnErrorEvent(ErrorServerEventArgs e)
        {
            EvtServerError(this, e);
        }
       
        public bool IsActive
        {
            get
            {
                return listenerSocket.Connected;
            }
        }

        public void InitDevice(string ip, int port, int bufferSize)
        {
            this.bufferSize = bufferSize;
            this.serverIP = ip;
            this.serverPort = port;
        }

        public void Start()
        {
            Start("serverSocketThread");
        }

        public void Start(string serverThreadName)
        {
            thread = new Thread(new ThreadStart(StartListening));
            thread.Name = serverThreadName;
            thread.IsBackground = true;

            thread.Start();
            Console.WriteLine("server Thread Starting..");
        }

        /// <summary>
        /// 发送一个流数据
        /// ①发送流的长度， ②发送流中字节数组
        /// 改进点：设定单次发送最大字节数组长度，按（总长度/长度）次，分批发送，根据需要针对发送字节数过滤、加密以及客户端连接状况的处理。
        /// </summary>
        public void Send(Socket ClientSocket, Stream Astream)
        {
            try
            {
                if (ClientSocket.Connected == false)
                {

                    throw (new Exception("没有连接客户端不可以发送信息!"));
                }

                Astream.Position = 0;
                byte[] byteData = new byte[bufferSize];

                int bi1 = (int)((Astream.Length + 8) / bufferSize);
                int bi2 = (int)Astream.Length;
                if (((Astream.Length + 8) % bufferSize) > 0)
                {
                    bi1 = bi1 + 1;
                }
                bi1 = bi1 * bufferSize;
                //流中字节数组的长度
                byteData[0] = System.Convert.ToByte(bi1 >> 24);
                byteData[1] = System.Convert.ToByte((bi1 & 0x00ff0000) >> 16);
                byteData[2] = System.Convert.ToByte((bi1 & 0x0000ff00) >> 8);
                byteData[3] = System.Convert.ToByte((bi1 & 0x000000ff));

                byteData[4] = System.Convert.ToByte(bi2 >> 24);
                byteData[5] = System.Convert.ToByte((bi2 & 0x00ff0000) >> 16);
                byteData[6] = System.Convert.ToByte((bi2 & 0x0000ff00) >> 8);
                byteData[7] = System.Convert.ToByte((bi2 & 0x000000ff));

                int n = Astream.Read(byteData, 8, byteData.Length - 8);

                while (n > 0)
                {
                    //首先发送，流长度
                    ClientSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), ClientSocket);
                    sendDone.WaitOne();
                    //再次，发送流内容
                    byteData = new byte[bufferSize];
                    n = Astream.Read(byteData, 0, byteData.Length);
                }
            }
            catch (Exception e)
            {
                OnErrorEvent(new ErrorServerEventArgs(e, ClientSocket));
            }
        }

        public void Send(Socket ClientSocket, byte[] cmd)
        {
            try
            {
                if (ClientSocket.Connected == false)
                {
                    throw (new Exception("没有连接服务器不可以发送信息!"));
                }

                //while (cmd.Length > 0)
                {
                    ClientSocket.BeginSend(cmd, 0, cmd.Length, 0, new AsyncCallback(SendCallback), ClientSocket);
                    sendDone.WaitOne();

                }
            }
            catch (Exception e)
            {
                
            }
        }

        public void Send(Socket ClientSocket, string cmdstr)
        {
            try
            {
                byte[] cmd = System.Text.Encoding.Default.GetBytes(cmdstr);
                if (ClientSocket.Connected == false)
                {
                    throw (new Exception("没有连接服务器不可以发送信息!"));
                }

                //while (cmd.Length > 0)
                {
                    ClientSocket.BeginSend(cmd, 0, cmd.Length, 0, new AsyncCallback(SendCallback), ClientSocket);
                    sendDone.WaitOne();

                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void Abort()
        {
            try
            {
                if (thread != null)
                {
                    Console.WriteLine(thread.Name + "  : " + thread.IsAlive);
                    if (thread.IsAlive)
                    {
                        thread.Join(3000);
                        thread.Abort();

                    }

                    if (null != listenerSocket)
                    {
                        listenerSocket.Close();
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        protected override void Dispose(bool disposing)
        {
            Abort();
        }

        private void StartListening()
        {
            try
            {
                listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ipAddress;
                if (serverIP.Trim() == "")
                {
                    ipAddress = IPAddress.Any;
                }
                else
                {
                    ipAddress = IPAddress.Parse(serverIP);
                }
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, serverPort);

                try
                {
                    listenerSocket.Bind(localEndPoint);
                }
                catch (SocketException se)
                {
                    OnErrorEvent(new ErrorServerEventArgs(se, listenerSocket));
                }
                //挂起连接队列的最大数==10
                listenerSocket.Listen(10);

                while (true)
                {
                    allDone.Reset();
                    listenerSocket.BeginAccept(new AsyncCallback(AcceptCallback), listenerSocket);
                    allDone.WaitOne();
                }
            }

            catch (Exception e)
            {
                OnErrorEvent(new ErrorServerEventArgs(e, listenerSocket));
            }
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            Socket client = null;
            try
            {
                Socket listenerSocket = (Socket)ar.AsyncState;
                client = listenerSocket.EndAccept(ar);

                StateObject state = new StateObject(bufferSize, client);
                state.workSocket = client;

                client.BeginReceive(state.buffer, 0, bufferSize, 0, new AsyncCallback(ReadCallback), state);

                OnClientConnectedEvent(client.RemoteEndPoint.ToString());
            }
            catch (Exception e)
            {
                OnErrorEvent(new ErrorServerEventArgs(e, client));
            }
            finally
            {
                allDone.Set();
            }
        }

        private void ReadCallback(IAsyncResult ar)
        {
            Socket handler = null;
            try
            {
                lock (ar)
                {
                    StateObject state = (StateObject)ar.AsyncState;
                    handler = state.workSocket;

                    int bytesRead =0;
                    try
                    {
                        bytesRead = handler.EndReceive(ar);
                    }
                    catch (SocketException se)
                    {
                        
                        OnClientDisConnectedEvent(handler.RemoteEndPoint.ToString());
                        handler.Close();
                        return;
                    }
                  

                    if (bytesRead <= 0)
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                    if (bytesRead > 0)
                    {
                        int ReadPiont = 0;
                        while (ReadPiont < bytesRead)
                        {
                            #region proc
                            if (state.Cortrol == 0 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 24) & 0xff000000;
                                state.packSize = bi1;
                                ReadPiont++;
                                state.Cortrol = 1;
                            }

                            if (state.Cortrol == 1 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 16) & 0x00ff0000;
                                state.packSize = state.packSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 2;
                            }

                            if (state.Cortrol == 2 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 8) & 0x0000ff00;
                                state.packSize = state.packSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 3;
                            }

                            if (state.Cortrol == 3 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = bi1 & 0xff;
                                state.packSize = state.packSize + bi1 - 4;
                                ReadPiont++;
                                state.Cortrol = 4;
                            }

                            if (state.Cortrol == 4 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 24) & 0xff000000;
                                state.residualSize = bi1;
                                ReadPiont++;
                                state.Cortrol = 5;
                                state.packSize -= 1;
                            }

                            if (state.Cortrol == 5 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 16) & 0x00ff0000;
                                state.residualSize = state.residualSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 6;
                                state.packSize -= 1;
                            }

                            if (state.Cortrol == 6 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = (bi1 << 8) & 0x0000ff00;
                                state.residualSize = state.residualSize + bi1;
                                ReadPiont++;
                                state.Cortrol = 7;
                                state.packSize -= 1;
                            }
                            if (state.Cortrol == 7 && ReadPiont < bytesRead)
                            {
                                long bi1 = state.buffer[ReadPiont];
                                bi1 = bi1 & 0xff;
                                state.residualSize = state.residualSize + bi1;
                                state.Datastream.SetLength(0);
                                state.Datastream.Position = 0;

                                ReadPiont++;
                                state.Cortrol = 8;
                                state.packSize -= 1;
                            }

                            if (state.Cortrol == 8 && ReadPiont < bytesRead)
                            {
                                int bi1 = bytesRead - ReadPiont;
                                int bi2 = (int)(state.residualSize - state.Datastream.Length);
                                if (bi1 >= bi2)
                                {
                                    state.Datastream.Write(state.buffer, ReadPiont, bi2);
                                    ReadPiont += bi2;
                                    OnReceiveEvent(new ReceiveEventArgs(state.Datastream, state.workSocket, this));
                                    state.Cortrol = 9;
                                    state.packSize -= bi2;
                                }
                                else
                                {
                                    state.Datastream.Write(state.buffer, ReadPiont, bi1);
                                    ReadPiont += bi1;
                                    state.packSize -= bi1;
                                }
                            }
                            if (state.Cortrol == 9 && ReadPiont < bytesRead)
                            {
                                int bi1 = bytesRead - ReadPiont;
                                if (bi1 < state.packSize)
                                {
                                    state.packSize = state.packSize - bi1;
                                    ReadPiont += bi1;
                                }
                                else
                                {
                                    state.Cortrol = 0;
                                    ReadPiont += (int)state.packSize;
                                }
                            }
                            #endregion proc
                        }

                        ProcessMsg(state.buffer, handler); 

                        if (handler.Connected == true)
                        {
                            handler.BeginReceive(state.buffer, 0, bufferSize, 0,
                                new AsyncCallback(ReadCallback), state);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                OnErrorEvent(new ErrorServerEventArgs(e, handler));
            }
        }

        private void SendCallback(IAsyncResult ar)
        {
            Socket client = (Socket)ar.AsyncState;
            try
            {
                int bytesSent = client.EndSend(ar);
            }
            catch (Exception e)
            {
                OnErrorEvent(new ErrorServerEventArgs(e, client));
          
            }
            finally
            {
                sendDone.Set();
            }
        }

        int i = 0;
        string tmpInfo = @"{'bingliID':'c0d-d3','yibaoID':null,'kaID':null,'keshiID':null}";
        void ProcessMsg(byte[] msg,Socket handler) 
        {
            string cmd = System.Text.Encoding.Default.GetString(msg);
            if (cmd.StartsWith("Request:"))
            {
                if (i%2==0)
                {
                    Send(handler, tmpInfo);
                }
                else
                {
                    Send(handler, tmpInfo);
                }
                i++;
            }
        }

        #region Component Designer generated code
        /**/
        /// <summary>Component Designer generated code
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {

        }
        #endregion
    }



    /**/
    /// <summary>
    /// 接收事件
    /// </summary>
    public class ReceiveEventArgs : EventArgs
    {
        private readonly Stream datastream;
        private readonly Socket serverSocket;
        private readonly SocketServer tcpIpServer;
        /**/
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="Astream">数据</param>
        /// <param name="ServerSocket">工作插座</param>
        /// <param name="TcpIpServer">提供服务的TCP/IP对象</param>
        public ReceiveEventArgs(Stream Astream, Socket ServerSocket, SocketServer TcpIpServer)
        {
            datastream = Astream;
            serverSocket = ServerSocket;
            tcpIpServer = TcpIpServer;
        }
        /**/
        /// <summary>
        /// 数据
        /// </summary>
        public Stream Astream
        {
            get { return datastream; }
        }
        /**/
        /// <summary>
        /// 工作插座
        /// </summary>
        public Socket ServerSocket
        {
            get { return serverSocket; }
        }
        /**/
        /// <summary>
        /// 提供TCP/IP服务的服务器对象.
        /// </summary>
        public SocketServer TcpIpServer
        {
            get { return tcpIpServer; }
        }
    }
    /**/
    /// <summary>
    /// 接收数据委托
    /// </summary>
    public delegate void ReceiveDataEvent(object sender, ReceiveEventArgs e);
    /**/
    /// <summary>
    /// 错误事件委托
    /// </summary>
    public class ErrorServerEventArgs : EventArgs
    {
        private readonly Exception error;
        private readonly Socket serverSocket;
        /**/
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="Error">数据</param>
        /// <param name="ServerSocket">问题插座</param>
        public ErrorServerEventArgs(Exception Error, Socket ServerSocket)
        {
            error = Error;
            serverSocket = ServerSocket;
        }
        /**/
        /// <summary>
        /// 数据
        /// </summary>
        public Exception Error
        {
            get { return error; }
        }
        /**/
        /// <summary>
        /// 问题插座
        /// </summary>
        public Socket ServerSocket
        {
            get { return serverSocket; }
        }
    }
    /**/
    /// <summary>
    ///错误事件委托 
    /// </summary>
    public delegate void ErrorServerEvent(object sender, ErrorServerEventArgs e);
}
